package com.ruoyi.gateway.filter;

import com.ruoyi.common.core.utils.uuid.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * Copyright (c) 2024, gitee
 * All rights reserved.
 *
 * @author qiupt@gitee.com
 * @description
 * @date 2024/10/22 16:12
 **/
@Component
@Slf4j
public class TraceInfoFilter implements GlobalFilter, Ordered {

    public static final String TRACE_ID = "traceId";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String traceId = null;
        List<String> traceIdList = request.getHeaders().get(TRACE_ID);
        if (traceIdList == null) {
            traceId = IdUtils.fastSimpleUUID();
//            log.info("生成TraceId：{}", traceId);
            request = exchange.getRequest().mutate().header(TRACE_ID, traceId).build();
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add(TRACE_ID, traceId);
            exchange = exchange.mutate().request(request).response(response).build();
        } else {
            traceId = traceIdList.get(0);
        }
        MDC.put(TRACE_ID, traceId);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
